package edu.ucsd.ccdb.rightClickPopupUtil;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.apache.xalan.lib.sql.SQLQueryParser;

import edu.ucsd.ccdb.MainConfiguration;
import edu.ucsd.ccdb.servlet.ServletSendReceive;
import edu.ucsd.ccdb.tagPopup.dataType.NIFOntologyTerm;
import edu.ucsd.irods.IRODSFileString;
import edu.ucsd.irods.SQLDBQuery;

public class RemoveAllOntoTagsListener implements ActionListener{
	
	private JTree tree;
	private Integer MPID;
	private String username;	
	private JFrame frame;
	
	public RemoveAllOntoTagsListener (JTree tree, JFrame frame, Integer MPID, String username) {
		this.tree = tree;
		this.username = username;
		this.MPID = MPID;
		this.frame = frame;
	}

	public void actionPerformed(ActionEvent e) {
		
		TreePath selectedPath = tree.getSelectionPath();
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();

		IRODSFileString file = (IRODSFileString) node.getUserObject();
		
		try {
			
			// delete the first node
			List<NIFOntologyTerm> data1 = SQLDBQuery.getDisplayOthoTag(MPID, file.getAbsolutePath() , username);
			for ( NIFOntologyTerm nifTerm: data1 ) {
				SQLDBQuery.deleteTagOthologyMPFile(MPID, username, file.getAbsolutePath(), nifTerm);
			}
			
			// do delete
			if (file.isDirectory()) {
				Queue<IRODSFileString> queue = new PriorityQueue<IRODSFileString>();
				queue.offer(file);
				
				IRODSFileString iterateFile = null;
				while ( (iterateFile = queue.poll() ) != null ) {
					
					String query = MainConfiguration.SERVLET_SERVER + MainConfiguration.SERVLET_PARAMETER + iterateFile.getAbsolutePath();
					List<IRODSFileString> listFiles = ServletSendReceive.getResponse( query );
					
					for (IRODSFileString element: listFiles) {
						
						if (element.isDirectory()) 
							queue.offer(element);

						List<NIFOntologyTerm> data = SQLDBQuery.getDisplayOthoTag(MPID, element.getAbsolutePath() , username);
						// remove tags, need account for empty
						
						for ( NIFOntologyTerm nifTerm: data ) {
							SQLDBQuery.deleteTagOthologyMPFile(MPID, username, element.getAbsolutePath(), nifTerm);
						}
					}
				}
			}
		}
		catch (SQLException e1 ) {
			e1.printStackTrace();
		}
		
		JOptionPane.showMessageDialog(frame, "All CCDB tags has been deleted", "Delete successfull", JOptionPane.INFORMATION_MESSAGE);
		
		
//		SQLDBQuery.deleteTagOthologyMPFile (MPID,  screeName, file.getAbsolutePath(), data);
	}

}
